<script lang="ts" setup>
import { computed, h, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Button, Col, message, Row, Space, Spin } from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import {
  getTisList,
  printTemplateAdd,
  printTemplateEdit,
  printTemplateUpdata,
  SupplyUserItems
} from '#/api/printTemplate'
import { supplyUserEdit } from '#/api/supplyUser'
import { upload_file_qiniu } from '#/api/upload'
import { upload_file_btw } from '#/views/backend/printTemplate/config'

const emit = defineEmits(['refresh'])
const tisList = ref<any>([])
const idsArr: any = ref([])
const inputDisabled = ref(true)

const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存'
})

const keyword = ref('')
const fetching = ref(false)

async function fetchRemoteOptions1({ keyword = '' }: Record<string, any>) {
  let quick_search = ''
  let initValue = ''
  const initKey = 'id'
  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
    if (initValue) {
      initValue = keyword.replace('initValue:', '').split(',')
    }
  } else {
    quick_search = keyword
  }
  const { list } = await SupplyUserItems({
    quick_search,
    page: 1,
    limit: 999,
    initKey,
    initValue,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.name,
    value: item.id,
  }))
}
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'Upload',
      componentProps: {
        accept: '.btw',
        customRequest: upload_file_btw,
        disabled: false,
        maxCount: 1,
        multiple: false,
        showUploadList: { showRemoveIcon: false, showPreviewIcon: false },
        listType: 'picture-card',
        onChange: (value: any) => {
          baseFormApi.setValues({ tpl_url: value.fileList[0].response }, false)
        },
      },
      fieldName: 'file',
      label: '模板文件(.btw)',
      renderComponentContent: () => {
        return {
          default: () => '点击上传',
        }
      },
    },
    {
      component: 'Input',
      componentProps: {
        disabled: true,
        allowClear: true,
        placeholder: '上传地址',
      },
      fieldName: 'tpl_url',
      label: '上传地址',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模板名称',
      },
      fieldName: 'name',
      label: '模板名称',
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      defaultValue: 1,
      componentProps: {
        options: [
          {
            label: '洗水唛',
            value: 1,
          },
          {
            label: '合格证',
            value: 2,
          },
        ],
      },
      fieldName: 'cate_id',
      label: '模板类型',
    },
    {
      component: 'Upload',
      componentProps: {
        accept: '.png,.jpg,.jpeg',
        customRequest: upload_file_qiniu,
        disabled: false,
        maxCount: 1,
        multiple: false,
        showUploadList: true,
        listType: 'picture-card',
      },
      fieldName: 'image',
      label: '模板图片',
      renderComponentContent: () => {
        return {
          default: () => '点击上传',
        }
      },
    },

    {
      component: 'RadioGroup',
      defaultValue: 0,
      componentProps: {
        options: [
          {
            label: '全部',
            value: 0,
          },
          {
            label: '指定',
            value: 1,
          },
        ],
      },
      fieldName: 'auth_type',
      label: '权限范围',
    },
    {
      component: 'ApiSelect',
      // 对应组件的参数
      dependencies: {
        show(values) {
          return values.auth_type === 0
        },
        triggerFields: ['auth_type'],
      },
      componentProps: () => {
        return {
          api: fetchRemoteOptions1,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword.value = value
          }, 300),

          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value || undefined,
          },
          showSearch: true,
          allowClear: true,
          immediate: false,
          mode: 'multiple',
          alwaysLoad: true,
          visibleEvent: 'onFocus',
          placeholder: '选中排除范围的账号，是没有该模板的权限',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value = ''
          },
        }
      },
      // 字段名
      fieldName: 'exclude_list',
      // 界面显示的label
      label: '排除账号',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },

    {
      component: 'ApiSelect',
      // 对应组件的参数

      dependencies: {
        show(values) {
          return values.auth_type === 1
        },
        triggerFields: ['auth_type'],
      },
      componentProps: () => {
        return {
          api: fetchRemoteOptions1,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword.value = value
          }, 300),

          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value || undefined,
          },
          showSearch: true,
          allowClear: true,
          immediate: false,
          mode: 'multiple',
          alwaysLoad: true,
          visibleEvent: 'onFocus',
          placeholder: '指定权限时，请选择关联的账号',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value = ''
          },
        }
      },
      // 字段名
      fieldName: 'auth_list',
      // 界面显示的label
      label: '指定账号',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'InputNumber',
      componentProps: {
        allowClear: true,
        placeholder: '如：66',
      },
      fieldName: 'width',
      label: '宽度',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      componentProps: {
        allowClear: true,
        placeholder: '如：120',
      },
      fieldName: 'height',
      label: '高度',
      rules: 'required',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        placeholder: '请输入模板备注',
      },
      fieldName: 'mark',
      label: '模板备注',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        placeholder: '请输入模板备注',
        rows: 5,
      },
      defaultValue: '{ }',
      help: '根据模板变量配置JSON，示例：{"GoodsName": "GoodsName", "GoodsCode": "GoodsCode" }',
      fieldName: 'tags_json',
      label: '标签变量',
    },
  ],
  wrapperClass: 'grid-cols-1',
})

const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  class: 'w-[50%] h-[100%]',
  appendToMain: true,
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { rowData, view } = modalApi.getData<Record<string, any>>()
      const parmas = {
        is_select: true,
        page: 1,
        initKey: 'id',
        select: true,
      }
      getTisList(parmas).then((res: any) => {
        tisList.value = res
      })

      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        if (Array.isArray(rowData)) {
          // 如果是多个编辑
          idsArr.value = rowData
          initData(rowData[0])
        } else {
          inputDisabled.value = true
          initData(rowData)
        }
      }
    }
  },
})

async function initData(rowData: any) {
  printTemplateEdit({ id: rowData }).then(async (response) => {
    const row = response.row
    row.image = [
      {
        url: `http://yyq.babiboy.com${row.image}`,
        name: `http://yyq.babiboy.com${row.image}`,
        uid:  `http://yyq.babiboy.com${row.image}`,
        status: 'success',
      },
    ]
    keyword.value = row.auth_type === 1 ? `initValue:${response.row.auth_list}` : `initValue:${response.row.exclude_list}`
    await baseFormApi.setValues(row, false)
  })
}

// 保存
async function save() {
  const { valid } = await baseFormApi.validate()
  if (!valid) {
    return
  }
  const values = await baseFormApi.getValues()
  if (values.image && values.image.length > 0) {
    const imgs = values.image.map((item: any) => {
      let imgPath = item.url ? item.url : (item.response ?? '')
      // 剔除环境变量前缀，只保存相对路径
      if (imgPath.startsWith('http://yyq.babiboy.com')) {
        imgPath = imgPath.replace('http://yyq.babiboy.com', '')
      }
      return imgPath
    })
    values.image = imgs[0]
  }
  values.file = undefined
  if (values.auth_type === 1) {
    values.exclude_list = []
  } else {
    values.auth_list = []
  }
  const parmas = {
    ...values,
  }

  if (values.id) {
    // 如果是多个编辑
    if (idsArr.value.length > 1) {
      printTemplateUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          const index = idsArr.value.indexOf(values.id)
          // 如果找到了对应的值，使用 splice 删除它
          if (index !== -1) {
            idsArr.value.splice(index, 1)
            initData(idsArr.value[0])
          }
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    } else {
      printTemplateUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          modalApi.close()
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    }
  } else {
    printTemplateAdd(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }
}
</script>

<template>
  <Modal :title="inputDisabled ? '编辑' : '新建'">
    <BaseForm />

    <div style="margin-left: 20px">
      <span style="font-size: 18px; color: red">标签变量说明：</span>
      <Row class="tips">
        <Col :span="8" v-for="(tagTitle, tagValue) in tisList" :key="tagValue">
          <span style="font: 14px">{{ tagTitle }}：{{ tagValue }}</span>
        </Col>
      </Row>

      <span style="font-size: 18px; color: red">排除账号：</span>
      <Row class="tips">
        <span style="font: 14px">选中的账号，没有该模板权限 （适合配置了私有模板，不需要公共模板）</span>
      </Row>

      <span style="font-size: 18px; color: red">指定账号：</span>
      <Row class="tips">
        <span style="font: 14px">指定的账号，才有该模板的权限（适合配置私有模板）</span>
      </Row>
    </div>
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button type="primary" @click="save()">{{ Text }}</Button>
        </Space>
      </div>
    </template>
  </Modal>
</template>

<style scoped>
.fina-box {
  padding: 10px 0;
}
.fina-btn {
  margin-bottom: 16px;
}
.red {
  color: red;
}
</style>
